package com.bwf.lgqingdan.mvp.model.impl;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.bwf.lgqingdan.db.SearchHistoryHandler;
import com.bwf.lgqingdan.entity.ResponseHotKeywords;
import com.bwf.lgqingdan.mvp.model.SearchModel;
import com.bwf.lgqingdan.utils.Apis;
import com.bwf.lgqingdan.utils.http.lib.HttpUtils;
import com.bwf.lgqingdan.utils.http.lib.Request;
import com.bwf.lgqingdan.utils.http.qingdan.HttpClient;

import java.util.List;

/**
 * Created by Administrator on 2016/11/19.
 */

public class SearchModelImpl implements SearchModel {
    private SearchHistoryHandler searchHistoryHandler;
    public SearchModelImpl(Context context) {
        this.searchHistoryHandler = new SearchHistoryHandler(context);
    }

    @Override
    public void loadHotSearchKeys(final Callback callback) {
        String url = Apis.API_HOT_SEARCH_KEYWORDS;
        Request.Builder builder = new Request.Builder()
                .url(url)
                .get();
        HttpClient.excute(builder, new HttpUtils.Callback() {
            @Override
            public void onResponse(String response) {
                ResponseHotKeywords responseHotKeywords = JSON.parseObject(response, ResponseHotKeywords.class);
                if(responseHotKeywords.getCode() == 0){
                    callback.loadHotSearchKeys(responseHotKeywords.getData().getKeywords());
                }else{
                    callback.loadFailed(responseHotKeywords.getMessage());
                }
            }

            @Override
            public void onError() {
                callback.loadFailed("连接服务器失败");
            }
        });
    }

    @Override
    public void loadHistorySearchKeywords(final Callback callback) {
        List<String> historyKeywords = searchHistoryHandler.queryByTimeDesc();
        callback.loadHistorySearchKeywordsSuccess(historyKeywords);
    }

    @Override
    public void addHistoryKeyword(String keyword,final Callback callback) {
        searchHistoryHandler.addKeyword(keyword);
        callback.refreshHistoryKeywords(searchHistoryHandler.queryByTimeDesc());
    }

    @Override
    public void clearHistoryKeywords() {
        searchHistoryHandler.clearAllDecords();
    }

}
